package it.amicosmanettone.whatsimage.login;

import it.amicosmanettone.whatsimage.ImagesActivity;
import it.amicosmanettone.whatsimage.MainActivity;
import it.amicosmanettone.whatsimage.R;
import it.amicosmanettone.whatsimage.SingleImageActivity;
import it.amicosmanettone.whatsimage.WarningActivity;

import java.util.Arrays;

import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MainFragment extends Fragment {
	
	private static final String TAG = "MainFragment";
	Session session = Session.getActiveSession();
	private UiLifecycleHelper uiHelper;
	Bundle extras;
	private TextView textBody;
	SharedPreferences sharedPref;
	Editor EDIT;
	
	private Session.StatusCallback callback = new Session.StatusCallback() {
	    @Override
	    public void call(Session session, SessionState state, Exception exception) {
	        onSessionStateChange(session, state, exception);
	    }
	};
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    uiHelper = new UiLifecycleHelper(getActivity(), callback);
	    uiHelper.onCreate(savedInstanceState);
	    this.extras = getActivity().getIntent().getExtras();
	}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View view = inflater.inflate(R.layout.activity_login, container,
					false);
			
			this.sharedPref = PreferenceManager.getDefaultSharedPreferences(getActivity());
			this.EDIT = sharedPref.edit();
			
			this.textBody = (TextView)view.findViewById(R.id.login_text_body);
			LoginButton buttonLogin = (LoginButton) view.findViewById(R.id.login_button_facebook);
			buttonLogin.setReadPermissions(Arrays.asList("basic_info"));
			buttonLogin.setFragment(this);
			
			return view;
		}
		
		@Override
		public void onActivityResult(int requestCode, int resultCode, Intent data) {
		    super.onActivityResult(requestCode, resultCode, data);
		    uiHelper.onActivityResult(requestCode, resultCode, data);
		}
		
		@SuppressWarnings("deprecation")
		private void onSessionStateChange(Session session, SessionState state, Exception exception) {
		    if (state.isOpened()) {
		        Log.i(TAG, "Logged in...");

		        // Request user data and show the results
		        Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

		            @Override
		            public void onCompleted(GraphUser user, Response response) {
		                if (user != null) {
		                    
		                	String welcomeText = getText(R.string.login_text_body).toString();
		                	textBody.setText(welcomeText + " " + buildUserInfoDisplay(user));
		                	EDIT.putString("userLogged", buildUserInfoDisplay(user)).commit();
		                	startNextActivity();
		                }
		            }
		            
		        });
		    } else if (state.isClosed()) {
		        Log.i(TAG, "Logged out...");
		        textBody.setText("");
		        EDIT.putString("userLogged","Guest").commit();
		        //startNextActivity();
		    }
		}
		
		private String buildUserInfoDisplay(GraphUser user) {
		    StringBuilder userInfo = new StringBuilder("");

		    
		    userInfo.append(String.format(user.getName()));

		    return userInfo.toString();
		}
		
		public void startNextActivity(){
			
			String warningText = null;
			String fromActivity = null;
			Intent goTo = null;
			
			if (extras != null) {
				warningText = extras.getString("warningText");
				fromActivity = extras.getString("fromActivity");
			}
			
			if(fromActivity.isEmpty()){
				
				goTo = new Intent(getActivity(), MainActivity.class);
    		
			}
			else if(fromActivity.equals("MAIN")){
				
				goTo = new Intent(getActivity(), MainActivity.class);
				
			}
			else if(fromActivity.equals("IMAGES")){
				
				goTo = new Intent(getActivity(), ImagesActivity.class);
				
			}
			else if(fromActivity.equals("IMAGE")){
				
				goTo = new Intent(getActivity(), SingleImageActivity.class);
				
			}
			final Intent warning = new Intent(getActivity(), WarningActivity.class);	

			if(warningText.equals(null)){

				goTo.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK );
				getActivity().startActivity(goTo);
				getActivity().overridePendingTransition(R.xml.translate_in, R.xml.translate_out);
				getActivity().finish();
				
			}else{
				
				warning.putExtra("warningText", warningText);
				warning.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK );
				getActivity().startActivity(warning);
        		getActivity().overridePendingTransition(R.xml.translate_in, R.xml.translate_out);
        		getActivity().finish();
				
			}
			
		}
		
		@Override
		public void onResume() {
		    super.onResume();
		    
		    if (session != null &&
			           (session.isOpened() || session.isClosed()) ) {
			        onSessionStateChange(session, session.getState(), null);
			    }

			uiHelper.onResume();
		}

		@Override
		public void onPause() {
		    super.onPause();
		    uiHelper.onPause();
		}

		@Override
		public void onDestroy() {
		    super.onDestroy();
		    uiHelper.onDestroy();
		}

		@Override
		public void onSaveInstanceState(Bundle outState) {
		    super.onSaveInstanceState(outState);
		    uiHelper.onSaveInstanceState(outState);
		}
		
}